package com.web;

import com.bean.Comment;
import com.bean.Post;
import com.dao.CommentDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/comment/add")
public class CommentAddServlet extends HttpServlet {
    /**
     * 添加一般使用 doPost 方法，比较安全
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取参数
        String postId = req.getParameter("postId");
        String content = req.getParameter("content");
        String author = req.getParameter("author");

        try {
            // 创建 post 对象
            Post post = new Post();
            // 获取 post 的 id
            post.setId(Long.parseLong(postId));
            // 创建对象并实现添加评论方法
            new CommentDao().addComment(new Comment(content, author, post));

            // 重定向页面
            resp.sendRedirect(req.getContextPath() + "/post?id=" + postId);
        } catch (Exception e) {
            // 把异常打印到控制台
            e.printStackTrace();
        }
    }
}
